/* global getApp Page wx */
const app = getApp()
var common = require('../../common.js');
var videolist = [];
let videoAd = null
let interstitialAd = null
let currentIndex = 1
let heigth=416
Page({
  onAdplay(e) {
    if (e.detail.type =="begin"){
      this.data.videoList[e.currentTarget.dataset.index].flag = false
      this.setData({
        videoList: this.data.videoList
      })
    }else{
      const {videoList } = this.data
      let that = this;
      videoList[e.currentTarget.dataset.index].flag = true
      this.setData({
        videoList
      })
     
      setTimeout(function () {
        videoList[e.currentTarget.dataset.index].flag = false
        that.setData({
          videoList
        })
      }, 10000);
    }
    },
  onAdload(e) {
    console.info(e)
    this.data.videoList[e.currentTarget.dataset.index].flag = false;
    this.setData({
      videoList: this.data.videoList
    })
  },
  
  data: {
    width: wx.getSystemInfoSync().windowWidth,
    height: wx.getSystemInfoSync().windowHeight,
    video_id: 0,
    categoryId:1,
    videoLoading: false,
    videoList: [],
    adBanner:"",
    location: [],
    isLock: false,  // 当前栗子无用，如果有些弹窗控制不住背后的视频列表滚动的话，isLock的作用就发挥出来了。
    localIndex: 0,
    noPageScroll: false,
    flag:true,
    showadd: true,
    userinfo: null,
    doLikeId:0,
    doLikeIndex:0,
    doLikeFlag:false,
    fullscreenFlag:false,
    fullscreenId:0
  },
  info: {
    videoPlayDetail: {} // 存放所有视频的播放位置
  },
  onLoad (options) {
    if (app.globalData && app.globalData.appInfo && app.globalData.appInfo.adBanner){
      this.setData({
        adBanner: app.globalData.appInfo.adBanner,
        adVideo: app.globalData.appInfo.adVideo,
        adStart: app.globalData.appInfo.adStart,
      })
    }else{
      this.setData({
        adBanner: 'adunit-182a9882ac20782b',
        adVideo: 'adunit-520b6809e32286d1',
        adStart: 'adunit-2f1d8a795490cde2',
      })
    }
    
    this.data.video_id = parseInt(options.video_id);
    this.data.categoryId = options.categoryId;
    const { videoLoading, videoList } = this.data
    this.videolist = [{
      "thumb": decodeURIComponent(options.thumb), "avatar": options.avatar, "click": options.click, "flag": true, "height": 400, "id": options.video_id, "info": options.info
      , "nickname": options.nickName, "src": options.src, "srcFlag": options.srcFlag, "played": true, "vlink": decodeURIComponent(options.vlink)
      , "title": options.title
    ,"width": 600}];
    this.setData({
      videoList: videoList.concat(this.formatVideoList1(this.videolist)),
    });
    this.getDetail(currentIndex);
    this.init();
    
    
 
    
  },
  onShow:function(){
  },
  onReady: function () {
    if (interstitialAd) {
      interstitialAd.show().catch(() => {
        interstitialAd.load()
          .then(() => interstitialAd.show())
          .catch(err => {
            console.log('插屏视频 广告显示失败')
          })
      })
    }
  },
  async init(){
    
    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-ca144edfc4d63ee9'
      })
      interstitialAd.onLoad(() => {
      })
      interstitialAd.onError((err) => { })
      interstitialAd.onClose(res => {
        app.globalData.isPlayed = false;
      })
    }
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-0bd5ae1b37c0e198'
      })
      videoAd.onLoad(() => {
       })
      videoAd.onError((err) => { })
      videoAd.onClose(res => {
          // 用户点击了【关闭广告】按钮
          if (res && res.isEnded) {
            if (this.data.doLikeFlag) {
            // 正常播放结束，可以下发游戏奖励
            wx.request({
              url: app.globalData.baseUrl + "/blade-video/userlike/like",
              method: 'POST',
              data: {
                token: common.token,
                openid: wx.getStorageSync('userInfo').openid,
                videoId: this.data.doLikeId,
                appId: wx.getAccountInfoSync().miniProgram.appId
              },
              success: res => {
                if (res.data.code == 200) {
                  if (res.data.data == 1) {
                    this.data.videoList[this.data.doLikeIndex].like = 1;
                  } else {
                    this.data.videoList[this.data.doLikeIndex].like = 0;
                  }
                  this.setData({ videoList: this.data.videoList });
                  let { doLikeFlag } = this.data
                  this.setData({
                    doLikeFlag: false
                  })
                  
                }
              }
            });
          } else if (this.data.fullscreenFlag){
            if (this.observerObj) this.observerObj.disconnect()
            let { fullscreenFlag } = this.data
            this.setData({
              fullscreenFlag: false
            })
            var videoContext = wx.createVideoContext("video" + this.data.fullscreenId, this);
             videoContext.requestFullScreen()
              videoContext.play();
        }
        
        } else {
          // 播放中途退出，不下发游戏奖励
            let { doLikeFlag } = this.data
            this.setData({
              doLikeFlag: false
            })
            let { fullscreenFlag } = this.data
            this.setData({
              fullscreenFlag: false
            })
        }
      })
    }
  },
  //下拉刷新
  reload:function(){

  },
  async getDetail(current) {
    wx.request({
      url: app.globalData.baseUrl + "/blade-video/video/playList",
      method: 'GET',
      data: {
        current: current,
        size:20,
        id: this.data.video_id,
        categoryId: this.data.categoryId
        
      },
      success: res => {
        if (res.data.code == 200) {
          const { videoLoading, videoList } = this.data
          this.videolist = res.data.data.records;
          var appInfo = app.globalData.appInfo;
          this.setData({
            videoList: videoList.concat(this.formatVideoList(this.videolist)),
          })
          let that = this;
          setTimeout(function () {
            videoList[0].flag = false
            that.setData({
              videoList: that.data.videoList
            })
          }, 10000);
          // setTimeout(
          //   this.handleVideoScroll
          // , 10000);   
          //this.handleVideoScroll()
        }
       
      }
    });

  },
  handleVideoScroll: function () {
    // 关键代码  
    if (this.observerObj) this.observerObj.disconnect()
    // relativeToViewport 这里指定对比的就是viewport,viewport的意思就是document中的可视区域
    this.observerObj = wx.createIntersectionObserver(this, { observeAll: true }).relativeToViewport({ top: -300, bottom: -300 });
    // 监听目标视频跟viewport相交区域的变化
    this.observerObj.observe(`.video-card`, this.controlVideos);
  },
  onUnload() {
    if (this.observerObj) this.observerObj.disconnect()
  },
  /**
   * 格式化视频列表
   * @param {Array} videoList 需要格式化的视频列表
   */
  formatVideoList1 (videoList) {
    const { width, height } = this.data
    return videoList.map(value => {
      let styleHight = width * value.height / value.width
      styleHight = styleHight > 0.7 * height ? 0.7 * height : styleHight
      return {
        ...value,
        styleHight: Math.floor(styleHight),
        currentTime: 0
      }
    })
  },
  formatVideoList(videoList) {
    const { width, height } = this.data
    return videoList.map(value => {
      let styleHight = width * value.height / value.width
      styleHight = styleHight > 0.7 * height ? 0.7 * height : styleHight
      return {
        ...value,
        styleHight: Math.floor(styleHight),
        currentTime: 0,
        played: false
      }
    })
  },
  // 设置播放的视频
  showVideoList (index) {
     let { videoList } = this.data
      let that=this;
      videoList = videoList.map(value => {
          value.played = false
          value.flag = true
          return value
      })
      if (index >= 0 && videoList[index]) {
          videoList[index].played = true
        videoList[index].isplayed = true
      setTimeout(function () {
        videoList[index].flag = false
        that.setData({
          videoList 
        })
        }, 10000);   
      }
      this.setData({
          videoList
      })
    
  },

  
  goback: function () {
    app.globalData.goback=1;
    wx.switchTab({
      url: '../../pages/index/index',
    });
  },
  
   controlVideos: function (res) {
     var appInfo = app.globalData.appInfo;
     let index =Math.round(res.id.substring(5));
     if (index % appInfo.adStartTime == 0&&index!=0) {
       app.globalData.isPlayed = true;
     } 
     let { videoList } = this.data
     if (res && res.intersectionRatio > 0) {
       // 视频在可视区域内，播放视频
       videoList = videoList.map(value => {
         value.played = false
         return value
       })
       this.showVideoList(index)
     } else {
       //  需要切换视频的时候，将当前视频暂停播放，并且通过handleVideoScroll 来播放下一个视频
       videoList = videoList.map(value => {
         value.played = false
         return value
       })
       // 当top < 0的时候，说明是在向上滑动，这时候currentPlayVideoIndex 需要加1
       if (res.boundingClientRect.top < 0) {
         this.showVideoList(index+ 1)
       } else {
         // 当top > 0的时候，说明是在向下滑动，这时候currentPlayVideoIndex 需要减1
         if (index - 1 < 0) {
           return;
         }
         this.showVideoList(index - 1)
       }
     }
     // 在适合的场景显示插屏广告  
     if (interstitialAd && app.globalData.isPlayed) {
       interstitialAd.show().catch(() => {
         interstitialAd.load()
           .then(() => interstitialAd.show())
           .catch(err => {
             console.log('插屏视频 广告显示失败')
           })
       })
     } 
  },
  // onReachBottom: function (e) {
  //   currentIndex++
  //   this.getDetail(currentIndex);
  // },
  scrollToUpper: function (e) {
    let { videoList } = this.data
    videoList = videoList.map(value => {
      value.played = false
      return value
    })
    this.showVideoList(0)
  },
  /**
 * 监听用户滑动页面事件--返回页面在垂直方向已滚动的距离（单位px）
 */
   onPageScroll(e) {
     if (!this.observerObj){
       this.handleVideoScroll()
     }
     
  // //  let { videoList, currentPlayVideoIndex } = this.data
  // //     var query = wx.createSelectorQuery();
  // //   query.select(`#video${currentPlayVideoIndex}`).boundingClientRect();
  // //     query.exec(function (res) {
  // //       heigth = res[0].height
  // //     })
  // //   let index = Math.ceil(e.scrollTop / heigth)
  // //   console.info(index)
  // //   if (currentPlayVideoIndex!=index){
  // //     currentPlayVideoIndex=index;
  // //     videoList = videoList.map(value => {
  // //       value.played = false
  // //       return value
  // //     })
  // //     this.setData({
  // //       videoList,
  // //       currentPlayVideoIndex
  // //     })
  // //     this.showVideoList(index)
  // //   }
   },
   // 隐藏提示
  hideAdd: function () {
    this.setData({ showadd: false });
    wx.setStorageSync('showAdd', false);
  },
  playEnded: function (option){
    let { videoList } = this.data
    videoList = videoList.map(value => {
      value.played = false
      return value
    })
    this.setData({
      videoList
    })
    var query = wx.createSelectorQuery(); 
    for (let i = 0; i < videoList.length; i++) {
      query.select(`#videoz${videoList[i].id}`).boundingClientRect()
    } 
    
    query.exec(function (res) {
      var miss = res[0].height * (Math.round(option.target.dataset.index+1));
      wx.pageScrollTo({
        scrollTop: miss-100,
        duration: 300
      });

    });
  },
  openDoLike: function (option){
    var videoContext = wx.createVideoContext("video" + option.currentTarget.dataset.id, this);
    videoContext.pause()
    let { doLikeFlag } = this.data
    this.setData({
      doLikeFlag: true
    })
    if (option.type) {
      this.data.doLikeId = option.currentTarget.dataset.id;
      this.data.doLikeIndex = option.currentTarget.dataset.index;
    } 

  },
  off:function(){
    let { doLikeFlag } = this.data
    this.setData({
      doLikeFlag: false
    })
    let { fullscreenFlag } = this.data
    this.setData({
      fullscreenFlag: false
    })
  },
  doLike: function (option) {
    
      if (videoAd) {
        videoAd.show()
          .catch(() => {
            videoAd.load()
              .then(() => videoAd.show())
              .catch(err => {
                console.log('激励视频 广告显示失败')
              })
          })
      }
  },
  loginForLike: function (e) {
    if (e.detail.userInfo) {
      var user = e.detail.userInfo;
      this.setData({
        isShowUserName: true,
        userInfo: e.detail.userInfo,
      })
      user.openid = app.globalData.openid;
      app._saveUserInfo(user);
      this.setData({ userinfo: user });
      var videoContext = wx.createVideoContext("video" + e.currentTarget.dataset.id, this);
      videoContext.pause()
      let { doLikeFlag } = this.data
      this.setData({
        doLikeFlag: true
      })
      if (e.type) {
        this.data.doLikeId = e.currentTarget.dataset.id;
        this.data.doLikeIndex = e.currentTarget.dataset.index;
      } 
    } else {
      app._showSettingToast('登陆需要允许授权');
    }
  },
  goNotice: function () {
    this.setData({ showadd: false });
    wx.setStorageSync('showAdd', false);
    wx.navigateTo({
      url: '../../graceUI/weplug-add-tips/index',
    });
    
  },
  onShareAppMessage: function (option) {
    var obj;
    if (option.target ==null){
      obj = {
        title: app.globalData.appInfo.shareTitle,
        path: 'pages/index/index',
        imageUrl: app.globalData.appInfo.shareIcon
      }
    }else{
      var appInfo = app.globalData.appInfo;
      var video = this.data.videoList[option.target.dataset.index];
      let vlink = encodeURIComponent(video.vlink);
      let thumb = encodeURIComponent(video.thumb);
      obj = {
        title: video.title,
        path: 'pages/playList/index?video_id=' + parseInt(video.id) + "&title=" + video.title + "&click=" + video.click + "&info=" + video.info + "&avatar=" + video.avatar + "&vlink=" + vlink + "&thumb=" + thumb + "&categoryId=" + this.data.categoryId + "&nickName=" + video.nickname + "&src=" + video.src + "&srcFlag=" + video.srcFlag,
        imageUrl: video.thumb
      }
    }
    
   
          // }
          return obj;
      


   
    // if (appInfo.shareOpen == 1) {
    //   obj = {
    //     title: appInfo.shareTitle,
    //     path: 'pages/playList/index?video_id =' + video.id,
    //     imageUrl: appInfo.shareIcon
    //   }
    // } else {
    
  },
  bindloadedmetadata:function(){
  },
  goNavigate: function (option){
    let flag = option.currentTarget.dataset.srcflag;
    if(flag==0){
      wx.navigateToMiniProgram({

        appId: option.currentTarget.dataset.appid,

        path: option.currentTarget.dataset.path,

        envVersion: 'release',

        extraData: {

          openId: app.globalData.openid    //需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据

        },

        success(res) {

          // 打开其他小程序成功同步触发

          wx.showToast({

            title: '跳转成功'

          });
        }

      })
    }else if(flag==1){

    }
  },
  goFullscreen: function (option){
    
    let { fullscreenFlag } = this.data
    this.setData({
      fullscreenFlag: true
    })
    if (option.type) {
      this.data.fullscreenId = option.currentTarget.dataset.id;
    } 
    var videoContext = wx.createVideoContext("video" + option.currentTarget.dataset.id, this);
     videoContext.pause()
  },
  screenChange(e) {
    let fullScreen = e.detail.fullScreen //值true为进入全屏，false为退出全屏
    if (!fullScreen) { //退出全屏
     this.handleVideoScroll();
    } 
  },
 
})
